package com.example.redismanual.dao.actionExamples;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class SimpleRedisLock {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    private ValueOperations<String, String> client;

    private static final String VALUE_OF_LOCK = "locking";

    private String key = "default_lock_key";

    public boolean acquire(){
        boolean result = this.client.setIfAbsent(this.key, VALUE_OF_LOCK);
        return result;
    }

    public boolean release(){
       return  stringRedisTemplate.delete(this.key);
    }

    //解决初始化报空指针错误问题 
    //https://blog.csdn.net/weixin_39029194/article/details/103470662
    @PostConstruct
    public void init(){
        this.client =  stringRedisTemplate.opsForValue();
    }

}
